package com.example.minisqlite;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 用户入口类：负责打开/关闭数据库，并暴露执行SQL的接口。
 */
public class Database implements Closeable {

    private final File file;
    private final StorageEngine storageEngine;
    private final WalManager walManager;
    private final Engine engine;
    private final SqlExecutor executor;

    private Database(File file, StorageEngine storageEngine, WalManager walManager, Engine engine, SqlExecutor executor) {
        this.file = file;
        this.storageEngine = storageEngine;
        this.walManager = walManager;
        this.engine = engine;
        this.executor = executor;
    }

    public static Database open(String path) throws IOException, SQLException {
        File f = new File(path);
        StorageEngine storage = new StorageEngine(f);
        WalManager wal = new WalManager(new File(path + ".wal"));
        wal.recover(storage);
        Engine engine = new Engine(storage, wal);
        SqlExecutor executor = new SqlExecutor(engine);
        return new Database(f, storage, wal, engine, executor);
    }

    public ResultSet execute(String sql) throws SQLException {
        return executor.execute(sql);
    }

    @Override
    public void close() throws IOException {
        engine.close();
        walManager.close();
        storageEngine.close();
    }
}
